<?php
namespace app\admin\controller;

use app\common\component\user\UserModel;

use app\common\model\Fruit as FruitModel;

class FruitSecond extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

    public function topUp() {
        return $this -> view -> fetch();
    }

	public function handleTopUp() {
		$post = $this -> request -> post();

		$findUser = UserModel::where('username', $post['username']) -> find();
		if(!$findUser) {
			echo '<meta charset="utf-8"><script>alert("用户不存在");window.location.href="/shuashuale/fruit/second/topUp";</script>';exit;
		}

		\think\Db::startTrans();
		try {
			if(!FruitModel::where('user_id', $findUser -> user_id) -> setInc('fruit_second_buy', $post['price'])) {
				throw new \Exception('收获种子失败, fruit setDec!');
			}

			$fruitSecondLogServiceCreate = (new \app\common\component\fruit\FruitSecondLogService()) -> create([
				'user_id' => $findUser -> user_id,
				'type' => 1,
				'active' => 1,
				'price' => $post['price'],
				'create_time' => time(),
				'remark' => '后台充值果子'
			]);
			if($fruitSecondLogServiceCreate['code'] != 0) {
				throw new \Exception($fruitSecondLogServiceCreate['message']);
			}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

				echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '");window.location.href="/shuashuale/fruit/second/topUp";</script>';exit;
		}
		
		echo '<meta charset="utf-8"><script>alert("充值成功");window.location.href="/shuashuale/fruit/second/topUp";</script>';exit;
	}
}
